// import { getData } from '@/api/ik/data/dataApi';
import { getTueMenuTree } from '@/api/ik/tureData/data'
import { getList } from '@/api/user/menu'
import { getInfo, login, logout, truegetInfo, truelogin } from '@/api/user/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { toTree } from '@/utils/ik/tree'

// 优化：处理头像 avatar 删除不需要的逻辑
const getDefaultState = () => {
  return {
    token: getToken(),
    userCode: '',
    userName: '',
    passWord: '',
    icon: '',
    // 处理过的menus
    menus: '',
    // 未处理的menus
    startMenus: '',
    menu: '/',
    ip: 'http://39.103.179.114:8085',
    fieldSecurityLevel: '',
    securityLevel: '',
    roleCode: '',
    roleName: '',
    rs1: '',
    yujingList: []
  }
}
const state = sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')).user : getDefaultState()

const mutations = {
  setIp: (state, ip) => {
    state.ip = ip
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  setSessionState: (state) => {
    sessionStorage.setItem('state', JSON.stringify({ user: state }))
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERCODE: (state, userCode) => {
    state.userCode = userCode
  },
  SET_USERNAME: (state, userName) => {
    state.userName = userName
  },
  SET_ICON: (state, icon) => {
    state.icon = icon
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_StartMENUS: (state, startMenus) => {
    state.startMenus = startMenus
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_FieldSecurityLevel: (state, fieldSecurityLevel) => {
    state.fieldSecurityLevel = fieldSecurityLevel
  },
  SET_SecurityLevel: (state, securityLevel) => {
    state.securityLevel = securityLevel
  },
  SET_RoleCode: (state, roleCode) => {
    state.roleCode = roleCode
  },
  SET_RoleName: (state, roleName) => {
    state.roleName = roleName
  },
  SET_PassWord: (state, ps) => {
    state.passWord = ps
  },
  SET_RS1: (state, rs1) => {
    state.rs1 = rs1
  },
  SET_YUJINGLIST: (state, yujingList) => {
    state.yujingList = yujingList
  }
}

const actions = {
  // 测试模式下用户登录
  testLogin({ commit, dispatch }, userInfo) {
    const { userCode, passWord } = userInfo
    commit('SET_USERCODE', userCode)
    return new Promise((resolve, reject) => {
      // 调用登录方法
      testLogin(userCode.trim(), passWord).then(response => {
        // 设置Token
        commit('SET_TOKEN', response)
        // 保存Token
        setToken(response)
        return response
      }).then(data => {
        // 加载用户权限
        return getList(userCode, getToken())
      }).then(response => {
        const tree = toTree(response, 'code', 'pCode')
        commit('SET_MENUS', tree)
        commit('setSessionState')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 正式环境下用户登录
  login({ commit, dispatch }, userInfo) {
    const { userCode, passWord } = userInfo

    commit('SET_USERCODE', userCode)
    return new Promise((resolve, reject) => {
      // 调用登录方法
      login(userCode.trim(), passWord).then(response => {
        // 设置Token
        commit('SET_TOKEN', response)
        // 保存Token
        setToken(response)
        return response
      }).then(data => {
        // 加载用户权限
        truegetInfo(getToken()).then(
          res => {
            commit('SET_FieldSecurityLevel', res.fieldSecurityLevel)
            commit('SET_SecurityLevel', res.securityLevel)
            commit('SET_RoleCode', res.roleCode)
            commit('SET_RoleName', res.roleName)
            commit('SET_USERNAME', res.userName)
            commit('SET_RS1', res.rs1)
          }
        )
        return getTueMenuTree(state.token, userCode)
      }).then(response => {
        const startMenus = JSON.parse(JSON.stringify(response))
        commit('SET_StartMENUS', startMenus)
        for (var i = 0; i < response.length - 1; i++) {
          for (let j = 0; j < response.length - 1 - i; j++) {
            const first = response[j].code * 1
            const last = response[j + 1].code * 1
            if (first > last) {
              const a = response[j]
              response[j] = response[j + 1]
              response[j + 1] = a
            }
          }
        }
        const tree = toTree(response, 'code', 'pCode')
        commit('SET_MENUS', tree)
        commit('setSessionState')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 测试获取用户信息
  testGetInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      testGetInfo(state.token).then(response => {
        commit('SET_USERNAME', response.userName)
        return response
      }).then(data => {
        // 加载用户权限
        return getList(data.userCode, getToken())
      }).then(response => {
        const tree = toTree(response, 'code', 'pCode')
        commit('SET_MENUS', tree)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 正式获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(getToken()).then(
        res => {
          commit('SET_FieldSecurityLevel', res.fieldSecurityLevel)
          commit('SET_SecurityLevel', res.securityLevel)
          commit('SET_RoleCode', res.roleCode)
          commit('SET_RoleName', res.roleName)
          commit('SET_USERNAME', res.userName)
          return res
        }
      ).then(data => {
        // 加载用户权限
        return getTueMenuTree(state.token, data.userCode)
      }).then(response => {
        const startMenus = JSON.parse(JSON.stringify(response))
        commit('SET_StartMENUS', startMenus)
        for (var i = 0; i < response.length - 1; i++) {
          for (let j = 0; j < response.length - 1 - i; j++) {
            const first = response[j].code * 1
            const last = response[j + 1].code * 1
            if (first > last) {
              const a = response[j]
              response[j] = response[j + 1]
              response[j + 1] = a
            }
          }
        }
        const tree = toTree(response, 'code', 'pCode')
        commit('SET_MENUS', tree)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.userCode, state.token).then(() => {
        removeToken()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 设置密码
  setpassword({ commit }, password) {
    commit('SET_PassWord', password)
  },
  // 重设Token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },
  // 删除Token
  remakeToken({ commit, dispatch, state }, params) {
    return new Promise((resolve, reject) => {
      // must remove  token  first
      removeToken()
      if (params === '2') {
        truelogin(state.userCode, state.passWord).then(response => {
          // 设置Token
          commit('SET_TOKEN', response)
          // 保存Token
          setToken(response)
          resolve(response)
        }).catch(reject())
      }
      if (params === '1') {
        login(state.userCode, state.passWord).then(response => {
          // 设置Token
          commit('SET_TOKEN', response)
          // 保存Token
          setToken(response)
          resolve(response)
        }).catch(reject())
      }
    })
  },
  // 设置当前菜单
  setMenu({ commit }, menu) {
    commit('SET_MENU', menu)
  },
  // 开启预警监控事件
  openWatch({ commit, state }) {

  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

